const Controllers = require('../../controllers/Controller.js').controller;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '新增商品',
    isDown: false,
    goodsImg: null,
    name: '',
    costPrice: '',
    salesPrice: '',
    vipPrice: '',
    array: [{ name: "", id: 1 }],
    setCommission: 0,
    isAddGoods: false,
    swiperImgList: [],
    addSwiperImgList: [],
    swiperImgIds: [],
    detailsImgList: [],
    addDetailsImgList: [],
    detailsImgIds: [],
    vip: false,
    integralState: false,
    heat: false,
    labelId: '',
    type: 1,
    rewardPrice: '',
    rewardProportion: '',
    stock: '',
    warnCount: '',
    goodsDetailsdata: '',
    goodsId: '',
    labelindex: 0,
    deleteRotationImgIds: [],
    deleteDetailImgIds: [],
    integral: '',
    isedit: true,
    rotationImgs:[],
    detailImgs:[]
  },
  //输入框赋值
  bindinput(e) {
    let type = e.currentTarget.dataset.type;
    let value = e.detail.value
    if (type == "name") {
      this.setData({
        name: value
      })
    } else if (type == "costPrice") {
      this.setData({
        costPrice: value
      })
    } else if (type == "salesPrice") {
      this.setData({
        salesPrice: value
      })
    } else if (type == "vipPrice") {
      this.setData({
        vipPrice: value
      })
    } else if (type == 'desc') {
      this.setData({
        desc: value
      })
    } else if (type == 'rewardPrice') {
      this.setData({
        rewardPrice: value
      })
    } else if (type == 'rewardProportion') {
      this.setData({
        rewardProportion: value
      })
    } else if (type == 'stock') {
      this.setData({
        stock: value
      })
    } else if (type == 'warnCount') {
      this.setData({
        warnCount: value
      })
    } else if (type == 'integral') {
      this.setData({
        integral: value
      })
    }

  },
  onLoad: function (options) {
    let title
    this.selectLabel()
    if (options.type) {
      this.setData({
        type: options.type
      })

      if (options.type == 1) {
        title = "新增商品"
      } else {
        title = "新增服务"
      }

    }
    if (options.isAddGoods) {
      this.setData({
        isAddGoods: options.isAddGoods
      })
    } else {
      if (options.id) {
        this.setData({
          goodsId: options.id
        })
        this.goodsDetails()
      }

      if (options.type == 1) {
        title = "编辑商品"
      } else {
        title = "编辑服务"
      }

    }
    if (options.isedit) {
      this.setData({
        isedit: options.isedit == '0' ? false : true
      })
    }
    this.setData({
      title
    })
  },
  selectLabel() {
    Controllers.selectLabel({ type: 1, shopId: wx.getStorageSync('shopId') }).then(res => {
      this.setData({
        array: res.data,
        labelId: res.data[0].id,
      })
    });
  },
  switchDown(e) {
    this.setData({
      isDown: e.detail.value
    })
  },
  switchvip(e) {
    this.setData({
      vip: e.detail.value,
    })
    if(this.data.vip==true){
      this.setData({
        heat: false
      })
    }
  },
  switchintegralState(e) {
    this.setData({
      integralState: e.detail.value
    })
  },
  switchheat(e) {
    this.setData({
      heat: e.detail.value,
    })
    if(this.data.heat==true){
      this.setData({
        vip: false
      })
    }
  },
  choose() {
    if (!this.data.isedit) {
      return
    }
    let that = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: 'https://www.xlshhr.com/beauty-industry/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'Content-Type': 'application/form-data',
            'sessionId': wx.getStorageSync('token')
          },
          success(res) {
            console.log(res);
            let src = JSON.parse(res.data)
            that.setData({
              goodsImg: src.data
            })
          }
        })
      }
    })
  },
  choosebanner() {
    if (!this.data.isedit) {
      return
    }
    let that = this;
    if (this.data.swiperImgList >= 5) {
      wx.showToast({
        title: '轮播图最多上传5张！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    wx.chooseImage({
      count: 5,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const tempFiles = res.tempFiles;
        console.log("tempFiles", tempFiles)
        for (let i = 0; i < tempFilePaths.length; i++){
          if (tempFilePaths[i].size > 1024 * 1024) {
            wx.showToast({
              title: '单张图片大不能超过1MB',
              icon: 'none',
              duration: 2000
            })
            return
          }
        } 
        that.uploadBanner(tempFilePaths, tempFilePaths.length, 0)
      }
    })
  },
  uploadBanner(tempFilePaths, leng, index) {
    let that = this
    wx.uploadFile({
      url: 'https://www.xlshhr.com/beauty-industry/api/img/uploadFile',
      filePath: tempFilePaths[index],
      name: 'image',
      formData: {
        'Content-Type': 'application/form-data',
        'sessionId': wx.getStorageSync('token')
      },
      success(res) {
        console.log(res);
        let src = JSON.parse(res.data)
        console.log("src", src)
        let swiperImgList = that.data.swiperImgList
        let addSwiperImgList = that.data.addSwiperImgList
        swiperImgList.push(src.data)
        addSwiperImgList.push(src.data)
        that.setData({
          swiperImgList,
          addSwiperImgList
        })
        if (leng == index) {
          return
        } else {
          index++
          that.uploadBanner(tempFilePaths, leng, index)
        }
      }
    })
  },
  choosedetail() {
    if (!this.data.isedit) {
      return
    }
    let that = this;
    wx.chooseImage({
      count: 9,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const tempFiles = res.tempFiles;
        for (let i = 0; i < tempFilePaths.length; i++){
          if (tempFilePaths[i].size > 1024 * 1024) {
            wx.showToast({
              title: '单张图片大不能超过1MB',
              icon: 'none',
              duration: 2000
            })
            return
          }
        } 
        that.uploadDdetail(tempFilePaths, tempFilePaths.length, 0)
      }
    })
  },
  uploadDdetail(tempFilePaths, leng, index){
    let that = this
    wx.uploadFile({
      url: 'https://www.xlshhr.com/beauty-industry/api/img/uploadFile',
      filePath: tempFilePaths[index],
      name: 'image',
      formData: {
        'Content-Type': 'application/form-data',
        'sessionId': wx.getStorageSync('token')
      },
      success(res) {
        console.log(res);
        let src = JSON.parse(res.data)
        console.log("src", src)
        let detailsImgList = that.data.detailsImgList
        let addDetailsImgList = that.data.addDetailsImgList
        detailsImgList.push(src.data)
        addDetailsImgList.push(src.data)
        that.setData({
          detailsImgList,
          addDetailsImgList
        })
        if (leng == index) {
          return
        } else {
          index++
          that.uploadDdetail(tempFilePaths, leng, index)
        }
      }
    })
  },
  bindPickerChange(e) {
    console.log(e)
    this.setData({
      labelId: this.data.array[e.detail.value].id,
      labelindex: e.detail.value
    })
  },
  setCommiss(e) {
    if (!this.data.isedit) {
      return
    }
    this.setData({
      setCommission: e.currentTarget.dataset.type
    })
  },
  goodsDetails() {
    Controllers.goodsDetails({ goodsId: this.data.goodsId }).then(res => {
      if (res.data.labelName.indexOf("/")) {
        res.data.labelName = res.data.labelName.split('/')
      } else {
        res.data.labelName = [res.data.labelName]
      }
      this.data.array.forEach((item, index) => {
        console.log("item", item)
        if (item.name == res.data.labelName) {
          this.setData({
            labelindex: index,
            labelId:this.data.array[index].id,
          })
        }
      });
      let swiperImgList = this.data.swiperImgList
      let swiperImgIds = this.data.swiperImgIds
      res.data.rotationImgs.forEach(item => {
        swiperImgList.push(item.image)
        swiperImgIds.push(item.id)
      })
      console.log("swiperImgList", swiperImgList)
      let detailsImgList = this.data.detailsImgList
      let detailsImgIds = this.data.detailsImgIds
      res.data.detailImgs.forEach(img => {
        detailsImgList.push(img.image)
        detailsImgIds.push(img.id)
      })
      console.log("detailsImgList", detailsImgList)
      this.setData({
        goodsDetailsdata: res.data,
        isDown: res.data.state == 1 ? true : false,
        goodsImg: res.data.image,
        name: res.data.name,
        costPrice: res.data.oldPrice,
        salesPrice: res.data.price,
        vipPrice: res.data.vipPrice,
        setCommission: res.data.rewardState,
        swiperImgList,
        rotationImgs:res.data.rotationImgs,
        detailImgs:res.data.detailImgs,
        swiperImgIds,
        detailsImgList,
        detailsImgIds,
        vip: res.data.vip == 1 ? true : false,
        integralState: res.data.integralState == 1 ? true : false,
        integral: res.data.integral ? res.data.integral : '',
        heat: res.data.heat == 1 ? true : false,
        rewardPrice: res.data.rewardPrice,
        rewardProportion: res.data.rewardProportion,
        stock: res.data.stock,
        warnCount: res.data.warnCount,
        desc: res.data.content
      })
      console.log("swiperImgIds", swiperImgIds)
    })
  },
  delectswiper(e) {
    if (!this.data.isedit) {
      return
    }
    let index = e.currentTarget.dataset.index;
    let itemsrc = e.currentTarget.dataset.src;
    let swiperImgList = this.data.swiperImgList
    // if (this.data.swiperImgIds.length > 0) {
    //   for(let item of this.data.swiperImgIds){
    //     if(itemsrc==item.image){
    //       let deleteRotationImgIds = this.data.deleteRotationImgIds
    //       deleteRotationImgIds.push(item.id)
    //       this.setData({
    //         deleteRotationImgIds
    //       })
    //     }
    //   }
     
    // }
    swiperImgList.splice(index, 1)
    this.setData({
      swiperImgList
    })
  },
  delectdetails(e) {
    if (!this.data.isedit) {
      return
    }
    let index = e.currentTarget.dataset['index'];
    let detailsImgList = this.data.detailsImgList;
    // let deleteDetailImgIds = this.data.deleteDetailImgIds
    // let itemsrc = e.currentTarget.dataset.src;
    // if (this.data.swiperImgIds.length > 0) {
    //   for(let item of this.data.detailsImgIds){
    //     if(itemsrc==item.image){
    //       let deleteDetailImgIds = this.data.deleteDetailImgIds
    //       deleteDetailImgIds.push(item.id)
    //       this.setData({
    //         deleteDetailImgIds
    //       })
    //     }
    //   }
     
    // }

    detailsImgList.splice(index, 1)
    this.setData({
      detailsImgList,
      // deleteDetailImgIds
    })
  },
  save() {
    if (!this.data.labelId) {
      wx.showToast({
        title: '请选择分类',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.costPrice) {
      wx.showToast({
        title: '请输入成本价',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.salesPrice) {
      wx.showToast({
        title: '请输入销售价',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.name) {
      wx.showToast({
        title: '请输入商品名称',
        icon: 'none',
        duration: 2000
      })
      return
    }
    // if (!this.data.desc) {
    //   wx.showToast({
    //     title: '请输入商品描述 ',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return
    // }
    if (!this.data.name) {
      wx.showToast({
        title: '请上传商品缩略图',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.setCommission == 1 && !this.data.rewardProportion) {
      wx.showToast({
        title: '请设置提成百分比',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.setCommission == 2 && !this.data.rewardPrice) {
      wx.showToast({
        title: '请设置提成固定金额',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.type == 1 && !this.data.stock) {
      wx.showToast({
        title: '请设置商品库存',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.type == 1 && !this.data.warnCount) {
      wx.showToast({
        title: '请设置预警库存',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.integralState == 1 && !this.data.integral) {
      wx.showToast({
        title: '请填入兑换积分',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let data = {}
    data.shopId = wx.getStorageSync('shopId');
    data.labelId = this.data.labelId;
    data.state = this.data.isDown ? 1 : 0;
    data.rewardState = this.data.setCommission;
    data.integralState = this.data.integralState ? 1 : 0;
    data.vip = this.data.vip ? 1 : 0;
    data.type = this.data.type;
    data.heat = this.data.heat ? 1 : 0;
    data.oldPrice = this.data.costPrice;
    data.price = this.data.salesPrice;
    data.name = this.data.name;
    data.content = this.data.desc || '';
    data.image = this.data.goodsImg;
    data.integral = this.data.integral;
    data.rewardProportion = this.data.rewardProportion ? this.data.rewardProportion : '';
    data.stock = this.data.stock ? this.data.stock : '';
    data.warnCount = this.data.warnCount ? this.data.warnCount : '';
    data.vipPrice = this.data.vipPrice;
    data.rewardPrice = this.data.rewardPrice ? this.data.rewardPrice : '';
    data.rotationImgs = this.data.swiperImgList.join(',')
    let detailsImgList=this.data.detailsImgList
    if(this.data.deleteDetailImgIds.length>0){
      for(let i=0;i<this.data.deleteDetailImgIds.length;i++){
        for(let j=0;j<this.data.detailsImgList.length;j++){
          if(this.data.deleteDetailImgIds[i].image==this.data.detailsImgList[j]){
            detailsImgList.splice(j, 1)
          }
        }
      }
    }
    data.detailImgs = detailsImgList.join(',')

    if (this.data.isAddGoods) {
      console.log(data)
      Controllers.saveGoods(data).then(res => {
        wx.showToast({
          title: '保存成功！',
          icon: 'success',
          duration: 2000
        })
        setTimeout(res => {
          wx.navigateBack({ //返回
            delta: 1
          })
        })
      });
    } else {

      data.deleteRotationImgIds = this.data.swiperImgIds.join(',')
      data.deleteDetailImgIds = this.data.detailsImgIds.join(',')
      data.id = this.data.goodsId
      data.rotationImgs = this.data.swiperImgList.join(',')
      data.detailImgs = this.data.detailsImgList.join(',')
      console.log(data)

      Controllers.updateGoods(data).then(res => {
        wx.showToast({
          title: '保存成功！',
          icon: 'success',
          duration: 2000
        })
        setTimeout(res => {
          wx.navigateBack({ //返回
            delta: 1
          })
        })
      });
    }
  },
  delete() {
    let data = {
      shopId: wx.getStorageSync('shopId'),
      goodsId: this.data.goodsId
    }
    Controllers.delGoods(data).then(res => {
      wx.showToast({
        title: '删除成功！',
        icon: 'success',
        duration: 2000
      })
      setTimeout(res => {
        wx.navigateBack({ //返回
          delta: 1
        })
      })
    });
  },
  preview(event) {
    let currentUrl = event.currentTarget.dataset.src
    let lists=event.currentTarget.dataset.lists
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: lists // 需要预览的图片http链接列表
    })
  },
})